package com.aaa.pay.service.impl;

import com.aaa.entity.AccountOrder;
import com.aaa.entity.Member;
import com.aaa.member.dao.MemberDao;
import com.aaa.pay.dao.AccountOrderDao;
import com.aaa.pay.service.AccountOrderService;
import com.aaa.util.HttpClient;
import com.aaa.vo.AccountOrderVo;
import com.aaa.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author JYH
 * @version 1.0
 * @date 2023/3/6 10:18
 */
@Service
public class AccountOrderServiceImpl extends ServiceImpl<AccountOrderDao, AccountOrder> implements AccountOrderService {

    @Autowired
    private AccountOrderDao accountOrderDao;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MemberDao memberDao;

    @Value("${weixin.appid}")
    private String appid;
    @Value("${weixin.mch_id}")
    private String mchid;
    @Value("${weixin.api_key}")
    private String apiKey;
    @Override
    public Result createNative(AccountOrderVo accountOrderVo) {

        //先创建一个支付订单
        AccountOrder accountOrder = new AccountOrder();
        accountOrder.setMemberId(accountOrderVo.getMemberId());
        accountOrder.setMoney(accountOrderVo.getAmount());
        accountOrder.setState(0);
        accountOrder.setAddtime(new Date());
        int insert = accountOrderDao.insert(accountOrder);
        //获取创建订单的id
        Integer id = accountOrder.getId();

        //1.订单号查询订单信息
        QueryWrapper<AccountOrder> wrapper=new QueryWrapper<>();
        wrapper.eq("id",id);
        wrapper.eq("state",0);
        AccountOrder accountOrder1 = accountOrderDao.selectOne(wrapper);
        if(accountOrder1!=null){

            //请求参数的封装
            Map<String,String> params=new HashMap<>();
            params.put("appid",appid);
            params.put("mch_id",mchid);
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            params.put("out_trade_no",id.toString());
            params.put("body","WeChatPay");
            params.put("total_fee",new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue()+"");
            params.put("spbill_create_ip","127.0.0.1");//真实服务器的ip
            params.put("notify_url","http://localhost:8080/pay/back");//支付成功后跳转的路径
            params.put("trade_type","NATIVE");
            try {
                //2.远程调用微信支付接口
                HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                //设置支持https协议的请求
                httpClient.setHttps(true);
                //设置xml格式的参数
                httpClient.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));
                //发送请求
                httpClient.post();

                //获取返回的结果
                String content = httpClient.getContent();
                //把xml转化为map
                Map<String, String> map = WXPayUtil.xmlToMap(content);
                System.out.println("map = " + map);
                if(map.get("result_code").equals("SUCCESS")){
                    Map<String,Object> result=new HashMap<>();
                    result.put("codeUrl",map.get("code_url"));
                    result.put("money",accountOrder1.getMoney());
                    result.put("id",accountOrder1.getId());
                    return new Result(2000,"获取二维码地址成功",result);
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }

        return new Result(5000,"订单失效",null);

    }

    @Override
    public Result queryPayStatus(Integer id) {

            Map<String,String> params=new HashMap<>();
            params.put("appid",appid);
            params.put("mch_id",mchid);
            params.put("out_trade_no",id.toString());
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            try {
                HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
                httpClient.setHttps(true);
                httpClient.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));

                httpClient.post();
                String content = httpClient.getContent();

                Map<String, String> map = WXPayUtil.xmlToMap(content);
                if(map.get("trade_state").equals("SUCCESS")){
                    //1.修改订单状态
                    AccountOrder accountOrder=new AccountOrder();
                    accountOrder.setState(1);
                    QueryWrapper<AccountOrder> wrapper=new QueryWrapper<>();
                    wrapper.eq("id",id);
                    wrapper.eq("state",0);
                    accountOrderDao.update(accountOrder,wrapper);
                    return new Result(2000,"支付成功",null);
                }

            }catch (Exception e){
                e.printStackTrace();
            }

            return new Result(5000,"支付失败",null);
    }

    @Override
    public Result addMoney(AccountOrderVo accountOrderVo) {
        //查询出用户信息
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",accountOrderVo.getMemberId());
        Member member = memberDao.selectOne(queryWrapper);
        Double accountBalance = member.getAccountBalance();
        double integration = member.getIntegration();

        //设置充值成功之后的账户余额，积分
        accountBalance=accountBalance+accountOrderVo.getAmount();
        integration=(integration+(accountOrderVo.getAmount()/10));
        member.setAccountBalance(accountBalance);

        //修改用户的账户余额，积分
        int update = memberDao.updateAccount(accountOrderVo.getMemberId(),accountBalance,integration);
        return new Result(2000,"充值成功",update);
    }

    @Override
    public Result createNative1(AccountOrderVo accountOrderVo) {

        //1.订单号查询订单信息
        QueryWrapper<AccountOrder> wrapper=new QueryWrapper<>();
        wrapper.eq("id",accountOrderVo.getId());
        wrapper.eq("state",0);
        AccountOrder accountOrder1 = accountOrderDao.selectOne(wrapper);

        if(accountOrder1!=null){
            //请求参数的封装
            System.out.println("=====进入微信=====");
            Map<String,String> params=new HashMap<>();
            params.put("appid",appid);
            params.put("mch_id",mchid);
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            params.put("out_trade_no",accountOrderVo.getId().toString());
            params.put("body","WeChatPay");
            params.put("total_fee",new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue()+"");
            params.put("spbill_create_ip","127.0.0.1");//真实服务器的ip
            params.put("notify_url","http://localhost:8080/pay/back");//支付成功后跳转的路径
            params.put("trade_type","NATIVE");
            try {
                //2.远程调用微信支付接口
                HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                //设置支持https协议的请求
                httpClient.setHttps(true);
                //设置xml格式的参数
                httpClient.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));
                //发送请求
                httpClient.post();

                //获取返回的结果
                String content = httpClient.getContent();
                //把xml转化为map
                Map<String, String> map = WXPayUtil.xmlToMap(content);
                System.out.println("map = " + map);
                if(map.get("result_code").equals("SUCCESS")){
                    Map<String,Object> result=new HashMap<>();
                    result.put("codeUrl",map.get("code_url"));
                    result.put("money",accountOrder1.getMoney());
                    result.put("id",accountOrder1.getId());
                    return new Result(2000,"获取二维码地址成功",result);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        return new Result(5000,"订单失效",null);
    }

    @Override
    public Result createMQ(Integer id) {
        String s1 = id.toString();
        //确保消息传到交换机
//                rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
//                    @Override
//                    public void confirm(CorrelationData correlationData, boolean b, String s) {
//                        if (b==false){
//                            //弥补机制--重新发送--取消订单--业务
//                            rabbitTemplate.convertAndSend("accountOrder_exchange","",s1);
//
//                        }
//                    }
//                });
                rabbitTemplate.convertAndSend("accountOrder_exchange","",""+s1);
                return new Result(2000,"成功",null);
    }

}

